import React from "react";
import {
 
  Input,
  Button,
  Spin,
  Modal,
  Space,
  Breadcrumb,
  Table,
  Tooltip,
  message,
  Popconfirm,
} from "antd";
import {
  EditFilled,
  DeleteFilled,
  PlusCircleOutlined,
} from "@ant-design/icons";
import { Link } from "react-router-dom";
import * as XLSX from "xlsx";
import {
  _addClass,
  _addOClass,
  _delClass,
  _delSomeClass,
  _getClassList,
  _updateClass,
} from "../../../../utils/class/idnex";
class NewsList extends React.Component {
  state = {
    selectedRowKeys: [], // Check here to configure the default column
    isLoading: false,
    a_visible: false,
    e_visible: false,
    confirmLoading: false,
    typeName: "",
    classList: null,
    class_id: null,
    class_num: null,
    class_name: null,

    inputKey: Math.random(), //导入
  };
  getData = () => {
    this.setState({ isLoading: true });
    _getClassList()
      .then((res) => {
        if (res.status === 200 && res.data.code === 0) {
          // console.log(res.data.data);
          this.setState({ isLoading: false });
          const classList = res.data.data;
          for (let i = 0; i < classList.length; i++) {
            classList[i].key = classList[i].class_id;
            classList[i].control = classList[i].class_id;
          }
          this.setState({ classList: classList });
        }
      })
      .catch(() => {
        this.setState({ isLoading: false });
        message.error("服务器错误");
      });
  };
  componentDidMount = () => {
    this.getData();
  };
  editSource = (val) => {
    this.setState({
      e_visible: true,
      class_id: val.class_id,
      class_name: val.class_name,
      class_num: val.class_num,
    });
  };
  editHandle = () => {
    let tempData = {
      class_name: this.state.class_name,
      class_num: this.state.class_num,
    };

    _updateClass(this.state.class_id, tempData)
      .then((res) => {
        if (res.status === 200) {
          this.setState({
            e_visible: false,
          });
          message.success("修改成功");
          this.getData();
        }
      })
      .catch(() => {
        this.setState({ confirmLoading: false });
        message.error("服务器错误");
      });
  };
  deletSource = (val) => {
    if (this.state.selectedRowKeys.length) {
      let temp = {
        arr: this.state.selectedRowKeys,
      };
      _delSomeClass(temp)
        .then((res) => {
          if (res.status === 200 && res.data.code === 0) {
            if (res.data.data && res.data.data.code === -1) {
              message.warning(res.data.data.msg);
            } else {
              message.success("批量删除成功");
              this.getData();
            }
          }
        })
        .catch(() => {
          this.setState({ isLoading: false });
          message.error("服务器错误");
        });
    } else {
      _delClass(val)
        .then((res) => {
          console.log(res.data);
          if (res.status === 200 && res.data.code === 0) {
            if (res.data.data && res.data.data.code === -1) {
              message.warning(res.data.data.msg);
            } else {
              message.success("删除成功");
              this.getData();
            }
          }
        })
        .catch(() => {
          this.setState({ isLoading: false });
          message.error("服务器错误");
        });
    }
  };

  showModal = () => {
    this.setState({
      a_visible: true,
    });
  };
  handleOk = () => {
    this.setState({
      confirmLoading: true,
    });
    let tempData = {
      class_name: this.state.class_name,
      class_num: this.state.class_num,
    };

    _addOClass(tempData)
      .then((res) => {
        if (res.status === 200) {
          this.setState({
            a_visible: false,
            confirmLoading: false,
          });
          message.success("添加成功");
          this.getData();
        }
      })
      .catch(() => {
        this.setState({ confirmLoading: false });
        message.error("服务器错误");
      });
  };
  handleCancel = () => {
    this.setState({
      e_visible: false,
      a_visible: false,
    });
  };
  onInputChange = (e) => {
    console.log(e.target.name);
    let inputValue = e.target.value;
    let inputName = e.target.name;
    this.setState({
      [inputName]: inputValue,
    });
  };
  onImportExcel = (file) => {
    this.setState({ isLoading: true });

    // 获取上传的文件对象
    const { files } = file.target;
    // 通过FileReader对象读取文件
    const fileReader = new FileReader();
    fileReader.onload = (event) => {
      try {
        const { result } = event.target;
        // 以二进制流方式读取得到整份excel表格对象
        const workbook = XLSX.read(result, {
          type: "binary",
        });
        // 存储获取到的数据
        let params = XLSX.utils.sheet_to_json(
          workbook.Sheets[workbook.SheetNames[0]]
        );
        for (var i = 0; i < params.length; i++) {
          params[i].class_name = params[i].专业班级;
          delete params[i].专业班级;
          params[i].class_num = params[i].专业班级号;
          delete params[i].专业班级号;
        }
        let tempData = {
          data: params,
        };
        console.log(tempData);
        _addClass(tempData)
          .then((res) => {
            if (res.status === 200 && res.data.code === 0) {
              this.setState({ isLoading: false });
              this.getData();
              message.success("数据导入成功！");
            }
          })
          .catch(() => {
            this.setState({ isLoading: false });
            message.error("服务器错误");
          });
      } catch (e) {
        message.error("文件类型不正确！");
      }
      this.setState({
        inputKey: Math.random(),
      });
    };
    // 以二进制方式打开文件
    fileReader.readAsBinaryString(files[0]);
  };

  //点击buttom触发input type="file"的点击事件
  uploadFile = () => {
    this.refs.inputFile.click();
  };
  onSelectChange = (selectedRowKeys) => {
    console.log("selectedRowKeys changed: ", selectedRowKeys);
    this.setState({ selectedRowKeys });
  };
  render() {
    const columns = [
      {
        title: "专业班级号",
        dataIndex: "class_num",
      },
      {
        title: "专业班级",
        dataIndex: "class_name",
      },
      {
        title: "操作",
        dataIndex: "control",
        render: (text, record) => (
          <Space size="middle">
            <EditFilled
              onClick={this.editSource.bind(this, record)}
              style={{ color: "#95a5a6" }}
            />
            <Modal
              title="修改专业班级"
              visible={this.state.e_visible}
              onOk={this.editHandle}
              onCancel={this.handleCancel}
              width={300}
            >
              <Space direction="vertical">
                <Input
                  onChange={this.onInputChange}
                  value={this.state.class_num}
                  name="class_num"
                  allowClear
                />
                <Input
                  onChange={this.onInputChange}
                  value={this.state.class_name}
                  name="class_name"
                  allowClear
                />
              </Space>
            </Modal>
            <Popconfirm
              title="确认要删除吗？"
              okText="是"
              cancelText="否"
              onConfirm={this.deletSource.bind(this, text)}
            >
              <DeleteFilled style={{ color: "#7f8c8d" }} />
            </Popconfirm>
          </Space>
        ),
      },
    ];

    const {  selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <div>
        <div className="stu-header">
          <Breadcrumb style={{ margin: "16px 0" }}>
            <Breadcrumb.Item>
              <Link to="/admin/h">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>专业班级</Breadcrumb.Item>
          </Breadcrumb>
          <Space>
            <Button
              icon={<PlusCircleOutlined />}
              onClick={this.showModal}
              type="primary"
            >
              添加
            </Button>
            <Modal
              title="添加班级名称"
              visible={this.state.a_visible}
              onOk={this.handleOk}
              confirmLoading={this.state.confirmLoading}
              onCancel={this.handleCancel}
              width={300}
            >
              <Space direction="vertical">
                <Input
                  onChange={this.onInputChange}
                  addonBefore="专业班级号"
                  name="class_num"
                  allowClear
                />
                <Input
                  onChange={this.onInputChange}
                  name="class_name"
                  addonBefore="专业班级"
                  allowClear
                />
              </Space>
            </Modal>
            <Tooltip placement="topLeft" title="仅支持 .xlsx、.xls 格式的文件">
              <Button
                icon={<PlusCircleOutlined />}
                onClick={this.uploadFile}
                type="primary"
              >
                导入
                <input
                  type="file"
                  key={this.state.inputKey}
                  accept=".xlsx, .xls"
                  onChange={this.onImportExcel}
                  hidden
                  ref="inputFile"
                />
              </Button>
            </Tooltip>
          </Space>
        </div>

        <div className="admin-body" style={{ padding: 15, minHeight: 360 }}>
          <Spin tip="Loading..." spinning={this.state.isLoading}>
            <Table
              columns={columns}
              dataSource={this.state.classList}
              rowSelection={rowSelection}
              pagination={{ pageSize: 10 }}
            />
          </Spin>
        </div>
      </div>
    );
  }
}

export default NewsList;
